<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\v2\model;

use think\Db;
use common\Utils;
use think\Model;
use think\cache\driver\Redis;
class Verify extends Model 
{	
    
    /**
     *  默认时间戳是字段  creat_time
     *  默认时间戳是格式  datetime
     */
	protected $name = 'user_verify';
    protected $createTime = 'create_time';
    protected $updateTime = false;
	protected $autoWriteTimestamp = 'datetime';


	public function sendVerify($phone,$type = 1,$uid = 0, $sms_type = 0)
	{
        $redis = new redis;
		$param['verify'] = create_rand(4, 'num');
		$param['account'] = $phone;
		$param['uid']    = $uid;

		$validate = validate($this->name);
		if (!$validate->check($param)) {
			$this->error = $validate->getError();
			return false;
		}
		
		$redis->select(15);
		$lockName = 'sendLock:'.$phone;

    	$lockInfo = $redis->get($lockName);
    	if($lockInfo)
    	{
    		$this->error = '验证码已发送,勿重复点击。';
    		return false;
    	}
        #获取系统配置
        $SystemConfig = model('api/SystemConfig')->getSysConfigList();
        if($SystemConfig['REG_SMS_CODE_DAILY_UP']<$this->sendLimt($phone)){
				$this->error = '今天该手机号短信发送已达上限';
				return false;	        	
        }		
		#type = 1  注册短信   type 2 找回密码
	
		if($type == 1){
			$user =  new User();
			if(!$user->ExistAccount($phone)){
				$this->error = '手机号已经被使用';
				return false;				
			}
		}else if($type == 2){
			$user =  new User();
			if($user->ExistAccount($phone)){
				$this->error = '手机号未被注册';
				return false;				
			}
		}
		
		if(!$sms_type)
		{
			$re = $this->sendSms($phone, $param['verify'], $type);
			if(!$re)
			{
				$this->error = $this->getError();
				return false;
			}
			$param['channel'] = $re;
		}else{
			#国都语音短信
			$msg = config('message_prefix') . "您的验证码为：".$param['verify'].'';
			$res = Utils::curl_heart_verify_yy($phone,$msg);
			if($res['status'] != 1){
				$this->error = '发送失败';
				return false;
			}
		}

		$redis->select(10);
		$param['create_date'] = time();
		$key = config('project_name').$phone;
        $ress  = $redis->hmset($key,$param);
        $res = $redis->expire($phone,1000);
		// $res = $this->data($param)->allowField(true)->save();
		if(!$ress){
			$this->error = '发送失败';
			return false;			
		}
		//十秒的误操
		$redis->select(15);
		$redis->set($lockName,1,10);
		return true;
	}
	/**
	 * [sendSms 发送验证码]
	 * @param  string  $phone  [description]
	 * @param  string  $verify [description]
	 * @param  integer $type   [description]
	 * @return [type]          [description]
	 */
	public function sendSms($phone = '', $verify = '', $type = 1)
	{
		if(!$phone || !$verify)
		{
			$this->error = '参数错误';
			return false;
		}
		//用redis做轮询短信
		$status = 1;//1 国都  2阿里大鱼 3 253
		$redis = new Redis;
		$redis->select(15);//选择库
		$name = 'rotation:'.date('Y-m-d').'-'.$phone;//key值
		$status = $redis->get($name)?: $status;
		$time = 86400;
		//默认 发送国都
		if($status == 2)
		{
			// 阿里大于
			$alidayuSms = Utils::curl_alidayu_verify($phone, $verify, $type, config('SYSTEM_NAME'));
			$redis->set($name, 1, $time);
			if($alidayuSms['code'] != 200){
				file_put_contents(LOGS_DIR_NAME."ALIError.txt", '时间:'.date('Y-m-d H:i:s').'---手机号:'.$phone.'---返回信息:'.json_encode($alidayuSms)."\n\n", FILE_APPEND);
				$this->error = '发送失败,请稍后重试!';
				return false;
			}
			Utils::SmsCount(1);
		}elseif($status == 1){
			# 国都短信
			$msg = config('message_prefix') . "您的验证码为：".$verify.'，5分钟内有效。';
			$res = Utils::curl_heart_verify($phone,$msg);
			$redis->set($name, 3, $time);
			if($res['status'] != 1){
				file_put_contents(LOGS_DIR_NAME."GDError.txt", '时间:'.date('Y-m-d H:i:s').'---手机号:'.$phone.'---返回信息:'.json_encode($res)."\n\n", FILE_APPEND);
				$this->error = '发送失败,请稍后重试';
				return false;
			}
			Utils::SmsCount(2);
		}else{
			// 253短信
			$msg = config('message_prefix') . "您的验证码是：".$verify.'，5分钟内有效。为了您的信息安全，请勿泄露验证码。';
			$res = Utils::curl_heart_Chuanglan_verify($phone,$msg);
			$redis->set($name, 2, $time);
			if($res['status'] != 1){
				file_put_contents(LOGS_DIR_NAME."CLError.txt", '时间:'.date('Y-m-d H:i:s').'---手机号:'.$phone.'---返回信息:'.json_encode($res)."\n\n", FILE_APPEND);
				$this->error = '发送失败,请稍后重试。';
				return false;
			}
		}
		return $status;
	}

	
	// public function checkVerify($phone,$verify,$uid)
	// {
	// 	$where['account']    = $phone;
	// 	$where['verify']     = $verify;
	// 	$where['uid']        = $uid;
	// 	$where['status']     = 1;
	// 	$where['pj_type']    = config('pj_type');

	// 	$res = $this->where($where)->order('id desc')->find();	     		
	//     $create_time = $res->create_time;
	// 	if(!$res){
	// 		$this->error = '验证码错误';
	// 		return false;			
	// 	}
	//     if((strtotime($create_time)+600)<time()){
	// 		$this->error = '验证码过期';
	// 		return false;
	//     }		
	// 	$this->where(['account' => $phone])->update(['status' =>0]);
	// 	return true;
	// }

	public function checkVerify($phone,$verify,$uid)
	{
		$where['account']    = $phone;
		$where['verify']     = $verify;
		$where['uid']        = $uid;
		$where['status']     = 1;
         
        $redis =  new redis();
        $redis->select(10);
        $key = config('project_name').$phone;
        $redis_hgetell_verify = $redis->hgetall($key);
        // p($redis_hgetell_verify);
        if(!$redis_hgetell_verify){
        	$this->error = '已经失效，请重新发送';
			return false;
        }
        // p($redis_hgetell_verify);
		// $res = $this->where($where)->order('id desc')->find();	     		
	    $create_time = $redis_hgetell_verify['create_date'];

        if($verify !== $redis_hgetell_verify['verify']){
        	$this->error = '验证码错误';
			return false;
        }


		// if(!$res){
		// 	$this->error = '验证码错误';
		// 	return false;			
		// }
	    if(($create_time+600)<time()){
			$this->error = '验证码过期';
			return false;
	    }		
		// $this->where(['account' => $phone])->update(['status' =>0]);
		$res = $redis->expire($key,60);
		return true;
	}

	public function sendLimt($phone)
	{
		$data = date("Y-m-d");
		$map['create_time'] = ['GT',$data];
		$map['account'] = $phone;
		return $this->where($map)->count('id');		
	}

}